<template>
  <div class="register-container">
    <div class="register-form">
      <div class="logo-section">
        <h1>用户注册</h1>
        <p>欢迎加入资源回收管理平台</p>
      </div>
      
      <el-form 
        ref="registerFormRef" 
        :model="registerForm" 
        :rules="registerRules" 
        @submit.prevent="handleRegister"
      >
        <el-form-item prop="role">
          <el-select
            v-model="registerForm.role"
            placeholder="请选择用户类型"
            size="large"
            style="width: 100%"
          >
            <el-option label="🟢 客户" value="customer">
              <span style="float: left">🟢 客户</span>
              <span style="float: right; color: #8492a6; font-size: 13px">个人用户，进行物品回收</span>
            </el-option>
            <el-option label="🔵 站点管理员" value="station_manager">
              <span style="float: left">🔵 站点管理员</span>
              <span style="float: right; color: #8492a6; font-size: 13px">管理回收站点</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名（3-50位，字母数字下划线）"
            size="large"
            prefix-icon="User"
          />
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码（6-20位）"
            size="large"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            size="large"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        
        <el-form-item prop="realName">
          <el-input
            v-model="registerForm.realName"
            placeholder="请输入真实姓名"
            size="large"
            prefix-icon="UserFilled"
          />
        </el-form-item>

        <el-form-item prop="phone">
          <el-input
            v-model="registerForm.phone"
            placeholder="请输入手机号"
            size="large"
            prefix-icon="Phone"
            maxlength="11"
          />
        </el-form-item>

        <el-form-item prop="email">
          <el-input
            v-model="registerForm.email"
            placeholder="请输入邮箱（QQ、163、Gmail等）"
            size="large"
            prefix-icon="Message"
          />
          <div class="form-tip">请使用常见邮箱服务商，用于接收系统通知</div>
        </el-form-item>

        <el-form-item prop="address">
          <el-input
            v-model="registerForm.address"
            type="textarea"
            placeholder="请输入地址（选填）"
            :rows="2"
            resize="none"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            size="large" 
            :loading="loading" 
            @click="handleRegister"
            class="register-button"
          >
            {{ loading ? '注册中...' : '立即注册' }}
          </el-button>
        </el-form-item>

        <el-form-item class="login-link">
          <span>已有账号？</span>
          <el-link type="primary" @click="goToLogin">立即登录</el-link>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { authAPI } from '@/api'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const registerFormRef = ref(null)

// 注册表单
const registerForm = reactive({
  role: 'customer', // 默认选择客户
  username: '',
  password: '',
  confirmPassword: '',
  realName: '',
  phone: '',
  email: '',
  address: ''
})

// 自定义验证规则
const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 表单验证规则
const registerRules = {
  role: [
    { required: true, message: '请选择用户类型', trigger: 'change' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 50, message: '用户名长度必须在3-50之间', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度必须在6-20之间', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validateConfirmPassword, trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { max: 100, message: '真实姓名长度不能超过100', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' },
    { 
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, 
      message: '请输入有效的邮箱地址', 
      trigger: 'blur' 
    }
  ]
}

// 方法
const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  try {
    await registerFormRef.value.validate()
    loading.value = true
    
    await authAPI.register({
      role: registerForm.role,
      username: registerForm.username,
      password: registerForm.password,
      realName: registerForm.realName,
      phone: registerForm.phone,
      email: registerForm.email,
      address: registerForm.address
    })
    
    // 注册成功，提示用户并跳转到登录页
    ElMessage.success('注册成功！请登录')
    
    // 等待一小段时间让用户看到提示
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    // 跳转到登录页面
    await router.push('/login')
  } catch (error) {
    console.error('Register error:', error)
    // 错误消息已经在拦截器中显示过了，这里不再重复显示
  } finally {
    loading.value = false
  }
}

const goToLogin = () => {
  router.push('/login')
}
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.register-form {
  width: 100%;
  max-width: 500px;
  padding: 40px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  max-height: 90vh;
  overflow-y: auto;
}

.logo-section {
  text-align: center;
  margin-bottom: 30px;
}

.logo-section h1 {
  margin: 0 0 10px 0;
  font-size: 28px;
  color: #333;
  font-weight: 600;
}

.logo-section p {
  margin: 0;
  font-size: 16px;
  color: #666;
}

.form-tip {
  color: #909399;
  font-size: 14px;
  margin-top: 5px;
  line-height: 1.5;
}

.register-button {
  width: 100%;
  height: 44px;
  font-size: 18px;
  font-weight: 500;
}

.login-link {
  text-align: center;
  margin-bottom: 0;
}

.login-link span {
  margin-right: 8px;
  color: #666;
  font-size: 16px;
}

/* 自定义滚动条 */
.register-form::-webkit-scrollbar {
  width: 6px;
}

.register-form::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.register-form::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 3px;
}

.register-form::-webkit-scrollbar-thumb:hover {
  background: #555;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .register-container {
    padding: 10px;
  }
  
  .register-form {
    padding: 30px 20px;
  }
  
  .logo-section h1 {
    font-size: 24px;
  }
}
</style>

